package com.aw.baselib.net.callback

import android.net.ParseException
import com.aw.baselib.R
import com.aw.baselib.base.AwBaseApplication
import com.aw.baselib.bean.rx.EventReLoginType
import com.aw.baselib.net.error.ApiException
import com.google.gson.JsonParseException
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * @author : hzw
 * @date : 2021/12/10
 */
class AwErrorSubscriber(private val mThrowCallback: AwErrorCallback?) : Consumer<Throwable> {
    override fun accept(e: Throwable) {
        if (null == mThrowCallback) {
            return
        }
        if (e is HttpException || e is UnknownHostException) {
            mThrowCallback.onFailure(
                UNKNOWN_CODE,
                AwBaseApplication.instance?.getString(R.string.common_net_server_abnormal_request)
            )
        } else if (e is SocketTimeoutException) {
            mThrowCallback.onFailure(
                UNKNOWN_CODE,
                AwBaseApplication.instance?.getString(R.string.common_net_server_abnormal_timeout)
            )
        } else if (e is ConnectException) {
            mThrowCallback.onFailure(
                UNKNOWN_CODE,
                AwBaseApplication.instance?.getString(R.string.common_net_server_abnormal_connect)
            )
        } else if (e is JsonParseException
            || e is JSONException
            || e is ParseException
        ) {
            mThrowCallback.onFailure(
                UNKNOWN_CODE,
                AwBaseApplication.instance?.getString(R.string.common_net_server_abnormal_parse)
            )
        } else if (e is ApiException) {
            val exception = e
            if (exception.isTokenExpried) {
                //处理token失效对应的逻辑
                EventBus.getDefault().postSticky(EventReLoginType(null))
            } else {
                mThrowCallback.onFailure(exception.errorCode, exception.msg)
            }
        } else {
            if (e.message != null && e.message!!.contains("failed") || e.message!!.contains("Failed")) {
                mThrowCallback.onFailure(
                    UNKNOWN_CODE,
                    AwBaseApplication.instance?.getString(R.string.common_net_abnormal)
                )
            } else {
                mThrowCallback.onFailure(UNKNOWN_CODE, e.message)
            }
        }
    }

    companion object {
        const val UNKNOWN_CODE = -1
    }
}